package 剑指offer.Month7_07.day17;

public class 把字符串转化为整数 {
    public int StrToInt (String s) {
        // write code here
        long res = 0;//用来做最后结果的接收
        int flag = 1;//用来辨别正负
        int i = 0;//用来遍历字符串
        while(i < s.length() &&s.charAt(i) == ' ') i++;
        if(i < s.length()){
            if(s.charAt(i) == '-'){
                flag = -1;
                i++;
            }else if(s.charAt(i) == '+'){
                i++;
            }
        }

        while(i < s.length()){
            if(s.charAt(i) >= '0'  && s.charAt(i) <= '9'){
                res = 10 * res + s.charAt(i) - '0';
                if(flag == -1 && res * -1 < Integer.MIN_VALUE) return Integer.MIN_VALUE;
                if(res > Integer.MAX_VALUE) return Integer.MAX_VALUE;
                i++;
            }else{
                break;
            }
        }
        int key = (int)res;
        key *= flag;
        return key;
    }
}
